<template>
  <view class="container">
    <view class="page__bd page__bd_spacing">
      <!-- 天气布局 -->
      <view class="home-header" :style="{color:header_bg.color,backgroundImage: weatherBg}">
        <view class="header-left single-line-text">
          <view v-if='address.address' class="hor-layout-center header-location" @click="openLocation">
            <image class="location-view" src="/static/ic_location.png"></image>
            <view class="ver-layout" style="margin-left: 7px;">
              <view>{{ filterLocation(address.address) }}</view>
              <view>{{ filterLocation(address.address, 1) }}</view>
            </view>
          </view>
          <view v-else>北京天气信息：</view>
          <view v-if="weatherObj" class="weather-info ver-layout">
            <view class="hor-layout-side-center">
              <view style="flex: 1.5">天气：{{ weatherObj.info }}</view>
              <view style="flex: 1">温度：{{ weatherObj.temperature + '℃' }}</view>
            </view>
            <view class="hor-layout-side-center">
              <view style="flex: 1.5">风向：{{ weatherObj.direct }}</view>
              <view style="flex: 1">空气：{{ weatherObj.aqi }}</view>
            </view>
          </view>
          <view v-else style="margin-top:10px">天气接口：{{ weatherObj.reason }}</view>
        </view>
        <view class="header-right">
          <!-- <lottie-view lottie_path="{{lottie_path}}" /> -->
<!--           <clock></clock> -->
          <clock-canvas></clock-canvas>
        </view>
      </view>
      <!-- 每日一言 -->
      <view class="home-center">
        <view class="every-day-title">每日一言</view>
        <view class="every-day-content">{{ oneNote.hitokoto }}</view>
        <view class="every-day-from">【{{ oneNote.from }}】</view>
      </view>
      <!-- 九宫格布局 -->
      <view class="flex-grid-layout home-grid">
        <block v-for="(item,index) in filterGrid(grids)" :key="index">
          <navigator :url="getGridUrl(item)" class="grid-item ver-layout-center"
                     :class="[{'no-bottom':gridNoBottom(index)},{'no-right':gridNoRight(index)}]">
            <view class="image-layout" :style="{background:gridItemBg(item)}">
              <icon class="icon-view fa fa-lg" :class="item.iconClass"/>
            </view>
            <view class="grid-item_label">{{ item.title }}</view>
          </navigator>
        </block>
      </view>
    </view>
  </view>
</template>

<script>
var gridColorJs = require('@/common/gridColor.js');
var util = require('@/common/util.js');
// import clock from 'components/custom/clock/clock.vue'
import clockCanvas from 'components/custom/clock-canvas/clock-canvas.vue'
import {updateVistorInfo} from "@/common/paltform.js"

export default {
  components: {
    clockCanvas,
    // clock
  },
  data() {
    return {
      loading: true,
      grids: [],
      address: {},
      weatherObj: {
        info: '',
        temperature: '',
        direct: "",
        aqi: "",
      },
      header_bg: {
        color: 'white',
        from_color: "#5ABEF9",
        to_color: "#5ABEF9"
      },
      userInfo: {},
      oneNote: ''
    }
  },
  computed: {
    weatherBg() {
      let header_bg = this.header_bg
      return `linear-gradient(to bottom, ${header_bg.from_color} , ${header_bg.to_color})`
    },
  },
  onLoad() {
    this.getHomeData()
    this.getOneNote()
    this.getLocationSetting()
  },
  onShow() {
  },
  methods: {
    gridNoRight(index) {
      return (index + 1) % 3 == 0
    },
    gridNoBottom(index) {
      return index + 1 > 3
    },
    gridItemBg(item) {
      return `linear-gradient(180deg, ${item.from_color} , ${item.to_color})`
    },
    filterLocation(location, flag = 0) {
      let sIndex = location.indexOf("市")
      if (flag == 0) return location.substring(0, sIndex + 1)
      else return location.substring(sIndex + 1, location.length)
    },
    filterGrid(grids) {
      let mGrids = []
      const onling = uni.getStorageSync('onling')
      grids.forEach(item => {
        if (onling && item.onlineCheck) mGrids.push(item)
        else mGrids.push(item)
      })
      // #ifdef MP
      return mGrids
      // #endif
      return grids
    },
    getGridUrl(item) {
      // #ifdef MP
      if (item.murl) return item.murl
      // #endif
      if (item.url) return item.url
    },
    //获取首页配置数据
    getHomeData() {
      uniCloud.callFunction({
        name: "database",
        data: {
          collection: 'home'
        }
      }).then(res => {
        console.log("getHomeData", res)
        // #ifdef MP-TOUTIAO
        res.result.data.forEach(item => {
          if (item.title === "表情包") {
            item.title = "开发中"
            item.url = ""
            item.murl = ""
          }
        })
        // #endif
        let grid_with_color = gridColorJs.getGridWithColor(res.result.data)
        this.grids = grid_with_color
        console.log("grids", grid_with_color)
      })
    },
    getOneNote() {
      uniCloud.callFunction({
        name: 'api-request',
        data: {
          action: 'getOneNote'
        }
      }).then(res => {
        let {hitokoto, from} = res.result
        this.oneNote = {hitokoto, from}
      })
    },
    async getLocationSetting() {
      if (this.$wechat && this.$wechat.isWechat()) {
        this.$wechat.location((res) => {
          this.location = res
          this.__convertLocation()
        })
      } else {
        // debugger
        this.getPermission().then(res=>{
          console.log("getPermission",res)
          uni.getLocation({
            type: 'gcj02',
            geocode: false,
            altitude: false,
            success: res => {
              console.log("getLocationSetting", res)
              this.location = res
              this.__convertLocation()
            },
            fail: (err) => {
              console.error("getLocationSetting", err)
            }
          })
        })
      }
    },
    async getPermission() {
      return new Promise((resolve, reject) => {
        // #ifdef MP-WEIXIN
        uni.authorize({scope: 'scope.userLocation',}).then(res=>{
          resolve(res)
        }).catch(err=>{
          reject()
        })
        // #endif
        // #ifndef MP-WEIXIN
        resolve()
        // #endif
      })
    },
    openLocation() {
      uni.openLocation({
        latitude: this.location.latitude,
        longitude: this.location.longitude,
      }).then(res => {
        console.log(res)
      })
    },
    getCityWeather(city) {
      uniCloud.callFunction({
        name: 'api-request',
        data: {
          action: 'getWeatherData',
          city
        }
      }).then(res => {
        // debugger
        console.log(res)
        let result = res.result
        this.weatherObj = result
        let address = this.address
        let weatherObj = this.weatherObj
        let updateObj = {
          address,
          weatherObj
        }
        updateVistorInfo(updateObj);
      }).catch(err => {
        // debugger
        console.error(err)
        let address = this.address
        updateVistorInfo({
          address
        });
      })
    },
    __convertLocation() {
      uniCloud.callFunction({
        name: 'api-request',
        data: {
          action: "convertLocation",
          location: this.location
        }
      }).then(res => {
        console.log("中文位置", res)
        // debugger
        let result = res.result
        if (result.status === 0) {
          let {ad_info, address, location} = result.result
          this.address = {ad_info, address, location}
          let city = ad_info.city
          this.getCityWeather(city.replace("市", ""))
        } else {
          console.error("__convertLocation", "获取信息失败，请重试！")
        }
      }).catch(err => {
        console.error("__convertLocation", err)
      })
    },
  }
}
</script>

<style>
.color-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 75px);
  /** 平铺宽度为50px的单元格 */
  grid-template-rows: 75px;
  /** 设置高度为50px */
  grid-auto-rows: 75px;
  /** 当容易高度不够时，多余的组件高度将怎么分配，默认的高度由单元格内容决定 */
  justify-content: center;
  /** 水平居中  */
  grid-gap: 5px;
  /** 水平和垂直间距为10rpx*/
  padding: 5px;
  background: white;
  border-radius: 2px;
}

.location-view {
  width: 20px;
  height: 20px;
  background: transparent;
}

.lottie-view {
  margin: 0 auto;
  width: 150px;
  height: 75px;
}

.share-view {
  width: 100%;
  position: absolute;
  left: 0px;
  bottom: 0px;
}

.home-header {
  height: 110px;
  margin-top: 15px;
  margin-bottom: 15px;
  border-radius: 8px;
  /* color: white; */
  padding: 12px;
  font-size: 14px;
  display: flex;
  flex-direction: row;
  box-shadow: 0 0 5px #bebcbc;
  /* background-image: linear-gradient(to right, #908282, #9b9b9b); */
}

.header-left {
  flex: 1;
}

.header-location {
  padding-bottom: 5px;
  margin-right: 10px;
  border-bottom: 1px solid #eaeaea;
}

.header-right {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  font-size: 15px;
}

.weather-info {
  margin-top: 8px;
  font-size: 14px;
}

.home-center {
  padding: 10px;
  color: white;
  background: #64c3c4;
  border-radius: 5px;
  margin: 15px 0px;
  box-shadow: 0 0 6px #bebcbc;
}

.home-grid {
  border: 1px solid #ededed;
  border-radius: 8px;
  box-shadow: 0 0 3px #bebcbc;
}

.image-layout {
  width: 30px;
  height: 30px;
  border-radius: 5px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  margin: 7px auto;
}

.icon-view {
  width: 20px;
  height: 30px;
  color: white;
  line-height: 30px;
  font-size: 18px;
  text-align: center;
}

.grid-item {
  width: calc(100% / 3 - 11px);
  padding: 10px 5px;
  border-right: 1px solid rgba(0, 0, 0, .1);
  border-bottom: 1px solid rgba(0, 0, 0, .1);
}

.grid-item.no-bottom {
  border-bottom: none;
}

.grid-item.no-right {
  border-right: none;
}

.grid-item_label {
  color: black;
  font-size: 14px;
}

.public-view {
  width: 200px;
  height: 50px;
}

.every-day-title {
  font-weight: bold;
  font-size: small;
}

.every-day-content {
  font-size: small;
  margin: 3px 0px;
}

.every-day-from {
  font-size: small;
  width: 100%;
  text-align: right;
}
</style>
